(function() {
	var MAX_SPECIFIED_ITEMS = 300;
	var MAX_SPECIAL_ITEMS = 50;
	var $status = $("#recommendation-status");
	var $form = $('#recommendation-options form');
	var $scope = $('#recommendation-options div.scope');
	var $special = $('div.special', $form);
	
	$(".start", $status).button({
		icons: {
			primary: "ui-icon-play"
		}
	}).click(function() {
		if ( $( this ).text() === "启动" ) {
			$.ajax({
				url: 'start',
				success: function( data, textStatus, req ) {
					var msg = req.getResponseHeader('msg');
					if (msg)
					{
						alert(msg);
						return false;
					}
					$('.msg-running', $status).show();
					$('.msg-stopped', $status).hide();
					$(".start", $status).button( "option", {
						label: "停止",
						icons: {
							primary: "ui-icon-pause"
						}
					});
				},
				error: function(jqXHR, textStatus, errorThrown) {
					alert(jqXHR.responseText);
				}
			});
		} else {
			$.ajax({
				url: 'stop',
				success: function( data, textStatus, req ) {
					var msg = req.getResponseHeader('msg');
					if (msg)
					{
						alert(msg);
						return false;
					}
					$('.msg-running', $status).hide();
					$('.msg-stopped', $status).show();
					$(".start", $status).button( "option", {
						label: "启动",
						icons: {
							primary: "ui-icon-play"
						}
					});
				},
				error: function(jqXHR, textStatus, errorThrown) {
					alert(jqXHR.responseText);
				}
			});
		}
	});
	
	var running = $status.attr('running');
	if ('true' == running)
	{
		$('.msg-running', $status).show();
		$('.msg-stopped', $status).hide();
		$(".start", $status).button( "option", {
			label: "停止",
			icons: {
				primary: "ui-icon-pause"
			}
		});
	}
	
	$('input[name="scope"]', $scope).change(function(){
		var scope = $(this).val();
		var $form = $(this).closest('form');
		if (scope == 1)
		{
			$('input[name="keyword"]', $form).removeAttr('disabled');
		}
		else
		{
			$('input[name="keyword"]', $form).attr('disabled', 'disabled');
		}
		if (scope == 2)
		{
			$('div.categories-selector', $form).slideDown('slow');
		}
		else
		{
			$('div.categories-selector', $form).hide();
		}
		if (scope == 3)
		{
			$('div.items-selector', $scope).slideDown('slow');
		}
		else
		{
			$('div.items-selector', $scope).hide();
		}
	});
	
	var scopeType = $scope.attr('type');
	if (scopeType)
	{
		$('input:radio[name="scope"]', $scope).removeAttr('checked');
		$('input:radio[value="' + scopeType + '"]', $scope).attr('checked', 'checked').change();
	}
	
	$('div.categories-selector input:checkbox', $scope).change(function(){
		var cid = $(this).parent().attr('value');
		var pid = $(this).parent().attr('parent');
		if (parseInt(pid) == 0)
		{
			var v = $(this).attr('checked');
			if (v)
			{
				$('div[parent="' + cid + '"] input').attr('checked', 'checked');
			}
			else
			{
				$('div[parent="' + cid + '"] input').removeAttr('checked');
			}
		}
	});
	
	function addTools($item)
	{
		var $deleteTool = $("<div class='delete-tool hide' title='删除'><img src='images/cross_small.png'/></div>");
		$item.append($deleteTool);
		$item.hover(
			function()
			{
				$deleteTool.show();
			},
			function()
			{
				$deleteTool.hide();
			}
		);
		$deleteTool.click(function(){
			$item.remove();
		});
	}
	
	var $specifiedItems = $('div.item');
	$specifiedItems.each(function(){
		addTools($(this));
	});
	
	var $dialog = $('#add-items-dialog');
	
	$dialog.dialog({
		autoOpen: false,
		modal: true,
		width: 800,
		height: 600,
		open: function(event, ui) {
			//todo
		},
		close: function(event, ui){
			$("#items-table").data('selection', []);
			$("#items-table input.selector").removeAttr('checked').trigger('change');
		}
	});
	
	$('button.add-item', $scope).button().click(function(){
		$dialog.dialog('option', 'buttons', {
			确定: function(){
				var $selectedRows = $('tr.row-selected', $dialog);
				if ($('div.selected-items .item', $scope).length + $selectedRows.length > MAX_SPECIFIED_ITEMS)
				{
					alert('最多支持' + MAX_SPECIFIED_ITEMS + '件宝贝。');
					return false;
				}
				$selectedRows.each(function(){
					var $row = $(this);
					var numIid = $row.attr('num_iid');
					if (!$('div.selected-items .item[num_iid="' + numIid + '"]', $scope).length > 0)
					{
						var $img = $('td.main-pic img', $row);
						var picUrl = $img.attr('src');
						var title = $img.attr('title');
						var $item = $('<div class="item border left"></div>');
						$item.attr('num_iid', numIid);
						$item.attr('title', title);
						$item.css('background', 'url(' + picUrl + ') center center no-repeat');
						$item.insertBefore('div.scope div.selected-items div.clear');
						addTools($item);
					}
				});
				$dialog.dialog('close');
			},
			取消: function(){
				$dialog.dialog('close');
			}
		});
		$dialog.dialog('open');
		return false;
	});
	
	$('input:checkbox', $special).change(function(){
		if ($(this).attr('checked'))
		{
			var version = $('#header').attr('version');
			if ('1' == version)
			{
				alert('高级版才支持特殊宝贝设置。升级后请关闭所有浏览器窗口并重新打开，新版本才会生效。');
				$(this).removeAttr('checked');
				return false;
			}
			$('.items-selector', $(this).parent().parent()).addClass('border').slideDown('slow');
		}
		else
		{
			$('.items-selector', $(this).parent().parent()).removeClass('border').hide();
		}
	});
	
	$('input:checkbox', $special).change();
	
	$('button.add-item', $special).button().click(function(){
		var $thisButton = $(this);
		$dialog.dialog('option', 'buttons', {
			确定: function(){
				var $selectedRows = $('tr.row-selected', $dialog);
				var $selectedItems = $('div.selected-items', $thisButton.parent());
				var showcasesCount = parseInt($status.attr('showcases'));
				if ($('.item', $selectedItems).length + $selectedRows.length > showcasesCount)
				{
					alert('不能超过您的橱窗总数：' + showcasesCount);
					return false;
				}
				if ($('.item', $selectedItems).length + $selectedRows.length > MAX_SPECIAL_ITEMS)
				{
					alert('最多支持' + MAX_SPECIAL_ITEMS + '件宝贝。');
					return false;
				}
				$selectedRows.each(function(){
					var $row = $(this);
					var numIid = $row.attr('num_iid');
					if (!$('.item[num_iid="' + numIid + '"]', $selectedItems).length > 0)
					{
						var $img = $('td.main-pic img', $row);
						var picUrl = $img.attr('src');
						var title = $img.attr('title');
						var $item = $('<div class="item border left"></div>');
						$item.attr('num_iid', numIid);
						$item.attr('title', title);
						$item.css('background', 'url(' + picUrl + ') center center no-repeat');
						$item.insertBefore($('div.clear', $selectedItems));
						addTools($item);
					}
				});
				$dialog.dialog('close');
			},
			取消: function(){
				$dialog.dialog('close');
			}
		});
		$dialog.dialog('open');
		return false;
	});
	
	$('button.save').button().click(function(){
		var mode = $('input[name="mode"]:checked', $form).val();
		var scopeType = $('input[name="scope"]:checked', $form).val();
		var keyword = $('input[name="keyword"]', $form).val();
		var sellerCids = null;
		var cids = null;
		var checkboxes = $("div[name='sellerCids'] input:checked", $form);
		if (checkboxes)
		{
			cids = [];
			checkboxes.each(function(){
				cids.push($(this).parent().attr('value'));
			});
		}
		if (cids)
		{
			sellerCids = cids.join();
		}
		var items = [];
		$('div.selected-items div.item', $scope).each(function(){
			var numIid = $(this).attr('num_iid');
			if (numIid)
			{
				items.push(numIid);
			}
		});
		var mustItemsEnabled = false;
		if ($('input:checkbox[name="must"]', $special).attr('checked'))
		{
			mustItemsEnabled = true;
		}
		var notItemsEnabled = false;
		if ($('input:checkbox[name="not"]', $special).attr('checked'))
		{
			notItemsEnabled = true;
		}
		var mustItems = [];
		$('div.must div.selected-items div.item', $special).each(function(){
			var numIid = $(this).attr('num_iid');
			if (numIid)
			{
				mustItems.push(numIid);
			}
		});
		var notItems = [];
		$('div.not div.selected-items div.item', $special).each(function(){
			var numIid = $(this).attr('num_iid');
			if (numIid)
			{
				notItems.push(numIid);
			}
		});
		var notKeywordInput = $('div.not input[name="notKeyword"]', $special);
		var notKeyword = notKeywordInput.val();
		$.ajax({
			url: 'save-options',
			data: {
				'mode.mode': mode,
				'scope.type': scopeType,
				'scope.keyword': keyword,
				'scope.sellerCids': sellerCids,
				'scope.items': items.join(),
				'special.mustItemsEnabled': mustItemsEnabled,
				'special.mustItems': mustItems.join(),
				'special.notItemsEnabled': notItemsEnabled,
				'special.notItems': notItems.join(),
				'special.notKeyword': notKeyword
			},
			type: 'POST',
			success: function(data, textStatus, req){
				var msg = req.getResponseHeader('msg');
				if (msg)
				{
					alert('保存失败。');
					return false;
				}
				alert('保存成功。');
			}
		});
		return false;
	});

})();
